package com.fh.shop.api.pay.biz;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.common.SystemConst;
import com.fh.shop.api.config.AlipayConfig;
import com.fh.shop.api.exception.PayException;
import com.fh.shop.api.member.mapper.IMemberMapper;
import com.fh.shop.api.mq.message.PayMessage;
import com.fh.shop.api.mq.product.PayProduct;
import com.fh.shop.api.order.biz.IOrderService;
import com.fh.shop.api.order.mapper.IOrderDetailMapper;
import com.fh.shop.api.order.mapper.IOrderMapper;
import com.fh.shop.api.order.po.Order;
import com.fh.shop.api.order.po.OrderDetail;
import com.fh.shop.api.product.mapper.IProductMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service("payService")
public class IPayServiceImpl implements IPayService {

    @Resource
    private IOrderMapper orderMapper;
    @Autowired
    private PayProduct payProduct;
    @Resource
    private IMemberMapper memberMapper;
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IOrderDetailMapper orderDetailMapper;
    @Value("${pay.subject}")
    private String subject;


    @Override
    public String alipay(String orderId) {
        //验证
        if (StringUtils.isEmpty(orderId)){
            throw new PayException(ResponseEnum.PAY_ORDER_ID_IS_NULL);
        }
        //订单是否存在
        Order order = orderMapper.selectById(orderId);
        if (order == null){
            throw new PayException(ResponseEnum.PAY_ORDER_ID_IS_ERROR);
        }
        //判断 是否重复发送请求
        int orderStatus = order.getOrderStatus().intValue();
        if (orderStatus > SystemConst.OrderStatus.WAIT_PAY){
            throw new PayException(ResponseEnum.PAY_ORDER_IS_PAYED);
        }
        //订单存在
        String totalPrice = order.getTotalPrice().toString();

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        Map<String,String> param = new HashMap<>();
        param.put("out_trade_no",orderId);
        param.put("total_amount",totalPrice);
        param.put("subject",subject);
        param.put("product_code","FAST_INSTANT_TRADE_PAY");
        String paramJson = JSON.toJSONString(param);

        alipayRequest.setBizContent(paramJson);


        //请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }



    }

    @Override
    public String aliNotify(Map<String, String[]> requestParams) {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = null;
        try {
            params = new HashMap<String,String>();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            /* 实际验证过程建议商户务必添加以下校验：
                1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
                2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
                3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
                4、验证app_id是否为该商户本身。
            */
            if(signVerified) {

                String trade_status = params.get("trade_status");
                if (trade_status.equals("TRADE_SUCCESS")){
                    //交易不成功
                    return "fail";
                }
                //验证成功
                //商户订单号
                String out_trade_no = params.get("out_trade_no");
                //从数据库查到的订单信息
                Order order = orderMapper.selectById(out_trade_no);
                if (order == null){
                    //订单不存在
                    return "fail";
                }
                //获取 total_amount 金额
                String total_amount = params.get("total_amount");
                BigDecimal totalPrice1 = order.getTotalPrice();
                String totalPrice = totalPrice1.toString();
                if (!total_amount.equals(totalPrice)){
                    //金额不一致
                    return "fail";
                }
                //卖家【商家】id
                String seller_id = params.get("seller_id");
                if (!seller_id.equals(AlipayConfig.seller_id)){
                    //商家不一致
                    return "fail";
                }
                //appid的验证
                String app_id = params.get("app_id");
                if (!app_id.equals(AlipayConfig.app_id)){
                    //addid不一致
                    return "fail";
                }


                //支付成功
                int orderStatus = order.getOrderStatus().intValue();
                if (orderStatus > SystemConst.OrderStatus.WAIT_PAY){
                    return "success";
                }
                //业务处理
                //更新订单状态
                Order orderInfo = new Order();
                orderInfo.setId(out_trade_no);
                orderInfo.setOrderStatus(SystemConst.OrderStatus.PAY_SUCCESS);
                orderMapper.updateById(orderInfo);
                //给会员加积分
//                Long memberId = order.getMemberId();
//                double score = Math.ceil(totalPrice1.doubleValue());
//                memberMapper.updateScore(memberId,score);
                //给订单对应的商品加销量
//                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
//                orderDetailQueryWrapper.eq("orderId",out_trade_no);
//                List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderDetailQueryWrapper);
//                orderDetails.forEach(x -> {
//                    productMapper.updateSale(x.getProductId(),x.getCount());
//                });

                PayMessage payMessage = new PayMessage();
                payMessage.setOrderId(out_trade_no);
                payMessage.setMemberId(order.getMemberId());
                payMessage.setTotalPrice(totalPrice1);
                payProduct.sendPayMessage(payMessage);

                return "success";
            }else {
                //验证失败
                return "fail";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
